// 封装文件上传
const multer = require('@koa/multer')
const COS = require('cos-nodejs-sdk-v5')
const { oss } = require('../env')
const { v4 } = require('uuid')
const path = require('node:path')
const { AVATAR_FORMAT_ERROR, AVATAR_SIZE_100KB_EXCEED } = require('../error/errorType')

// 本地策略
const localUpload = multer({
    storage: multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, './static')
        },
        filename: (req, file, cb) => {
            console.log('filename')
            cb(null, `file_${v4()}${path.extname(file.originalname)}`)
        }
    }),
    // limits: {
    //     fileSize: 100 * 1024, // 100KB
    // },
    // fileFilter: (req, file, cb) => {
    //     console.log(req)
    //     if (file.mimetype == 'image/png' || file.mimetype == 'image/jpeg') {
    //         cb(null, true)
    //     } else {
    //         cb(null, false)
    //     }
    // }
})

// 对象存储策略
const ossUpload = multer({
    storage: multer.memoryStorage()
})

// 具体的oss上传处理
const { secretId, secretKey, bucket, region } = oss
const cosObj = new COS({ SecretId: secretId, SecretKey: secretKey })
const ossUploadHandler = (target, file) => {
    return new Promise(async (resolve, reject) => {
        try {
            // 获取完整文件名和对应的buffer
            const { originalname, buffer } = file
            const [fileName, suffix] = originalname.split('.')
            // 上传
            const data = await cosObj.putObject({
                Bucket: bucket,
                Region: region,
                Key: `${fileName}-${v4()}.${suffix}`,
                Body: buffer,
            })
            if (data.statusCode == 200) {
                resolve(`https://${data.Location}`)
            } else {
                resolve('')
            }
        } catch (err) {
            reject(err)
        }
    })
}

module.exports = {
    localUpload,
    ossUpload,
    ossUploadHandler,
}